/* Psychiatry data */
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_YearCollapse

keep if inrange(minagec,10,50)

gen man=(koen==1)
keep pnr year man famany*

/** Use values from one year prior **/
sort pnr year
foreach var of varlist famany* {
by pnr: gen lag`var'=`var'[_n-1] if pnr==pnr[_n-1] 
replace `var'=lag`var'
}

save "I:\workdata\706727\Build\Data\ColSev_basechar", replace

/*** Psychiatric contacts ****/
clear all
cd "I:\workdata\706727\Build\Data"
use psychighfreq_AllAges_finalfull

gen year2=year if inrange(month,4,12)
replace year2=year-1 if inrange(month,1,3)

drop year
rename year2 year

keep if inrange(year,1995,2011)
keep if inrange(agec,10,50)

keep pnr year month agec Dpsyc Dpsychiatry Dpsyk_test Dtherapy hen19 hen10 hen11 mentaldiag Dsui asui pois pois_painkiller Dpsykhosp Dbamb_AnxDep Derp_AnxDep DPHosp_AnxDep 

merge 1:1 pnr year month using "J:\workdata\706727\Temp\extradata"
drop if _merge!=3
drop _merge

foreach var in sick disab sueduc cash_unemp2 cash_unemp cash_int educhelp sometrans dagp_unemp dagp_act ledyd forre re flexjob skaane intyd cash_dagexp  resf jobafk parleave {
qui sum year if !mi(`var') 
replace `var'=0 if mi(`var') & inrange(year,r(min),r(max))

gen byte D`var'=(`var'>0 & !mi(`var')) if inrange(year,r(min),r(max))
drop `var'
}
egen Dcash_any=rowmax(Dcash_unemp2 Dcash_unemp Dcash_int Dintyd Dcash_dagexp Deduchelp)
egen Ddisab_any=rowmax(Dledyd Dforre Dre Dflexjob Dskaane Dresf Djobafk Ddisab )
egen Ddagp_any=rowmax(Ddagp_unemp Ddagp_act)
egen Dallnonparleave=rowmax(Dsick Ddisab Dcash_unemp2 Dcash_unemp Dcash_int Deduchelp Ddagp_unemp Ddagp_act Dledyd Dforre Dre Dflexjob Dskaane Dintyd Dcash_dagexp  Dresf Djobafk)
egen Dmixlabortrans=rowmax(Dforre Dre Dflexjob Dskaane Dresf Djobafk)
drop Dcash_unemp Dcash_int Dintyd Dcash_dagexp Deduchelp Dledyd Dforre Dre Dflexjob Dskaane Dresf Djobafk Ddagp_unemp Ddagp_act

gcollapse (max) Dpsyc Dpsychiatry Dpsyk_test Dtherapy hen19 hen10 hen11 mentaldiag Dsui asui pois pois_painkiller Dpsykhosp Dbamb_AnxDep Derp_AnxDep DPHosp_AnxDep  (min) age=agec (mean) Dcash_any Ddisab_any Ddagp_any Dallnonparleave Dmixlabortrans Dsueduc earn inc assets , by(pnr year) fast

** Create lags **

sort pnr year
foreach var in Dpsyc Dpsychiatry Dpsyk_test Dtherapy hen19 hen10 hen11 mentaldiag Dsui asui pois pois_painkiller Dpsykhosp Dbamb_AnxDep Derp_AnxDep DPHosp_AnxDep Dcash_any Ddisab_any Ddagp_any Dallnonparleave Dmixlabortrans Dsueduc earn inc assets {
	forvalues i=1/5 {
	by pnr: gen lag`i'_`var'=`var'[_n-`i'] if pnr==pnr[_n-`i']
	}
}

keep pnr year age lag*

save "I:\workdata\706727\Build\Data\ColSev_lagvars", replace
